#coding=utf-8
from fastapi import Request,FastAPI,status 
 
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder
import re
from fastapi import HTTPException
from starlette.responses import Response
from starlette.types import ASGIApp
from src.utils.respone import fail
from src.core.life import REDIS

# 权限验证
class AuthMiddleware(BaseHTTPMiddleware):
    # 
    def __init__(self, app):
        super().__init__(app)

    # 
    async def dispatch(self, request: Request, call_next) -> Response:
        
        # 将数据库和redis相关挂载到requst上
        request.scope["redis"] = REDIS

        api = str(request.url).replace(str(request.base_url), '')
        notPApi = ["api/users/login"]
        
        # api过滤
        if (len(api) == 0 or (len(api) > 0 and re.match(r'api/', api))) and api not in notPApi:
            # 不在忽略内的接口需要进行token验证
            print("===未登录====", api)
            return fail(status_code=status.HTTP_401_UNAUTHORIZED, msg="请登录")
         
        request.scope["userInfo"] = "天才"
        # for it in request:
        #     print(it)
        response  = await call_next(request)
        response.status_code = status.HTTP_200_OK
        print(">>>>", )
        # 字段验证出错响应修改
        # if response.status_code == 422:
        #     return JSONResponse(
        #             status_code=status.HTTP_200_OK,
        #             content=jsonable_encoder({'masg': '权限不够'}))

        return response
    

     
